import time
from typing import List

from sys_intd.manager import McpServerManager
from sys_intd.schema import MCPCenterServerConfig
import psutil


def status(server_name: str = "cache-miss-audit") -> List[str]:
    """
    查看MCP服务运行状态

    Args:
        server_name: 服务名称

    Returns:
        状态信息列表
    """
    output_lines = []
    mcp_server_manager = McpServerManager()
    server_config = mcp_server_manager.get_server(server_name)
    python_cmd: List = [server_config.command, *server_config.args]
    output_lines.append(f"\n[bold cyan]check status server '{server_name}'")

    if len(python_cmd) < 2:
        output_lines.append(f"\n[bold cyan]'{server_name}' is not running\n")
        return output_lines

    server_path = python_cmd[1]

    for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'exe']):
        try:
            cmdline = proc.info['cmdline']  # 进程启动命令行，是一个列表，如 ['python3', 'xxx.py']
            process_name = proc.info['name']
            if not cmdline or len(cmdline) < 2:
                continue
            if process_name != 'python3' and process_name != 'python':
                continue
            if cmdline[0] !=python_cmd[0]:
                continue

            launched_script = cmdline[1] if len(cmdline) > 1 else ""

            if launched_script.endswith(server_path):
                url = server_config.url if isinstance(server_config, MCPCenterServerConfig) else "未知"
                output_lines.append(
                    f'''[bold]Find target process, pid: {proc.info['pid']}, startup cmd: {' '.join(cmdline)}''')
                output_lines.append(f"[green]服务正在运行[/]")
                output_lines.append(f"[bold]状态:[/] 活跃")
                output_lines.append(f"[bold]启动时间:[/] {time.ctime(proc.create_time())}")
                output_lines.append(f"[bold]CPU使用率:[/] {proc.cpu_percent(interval=0.1):.2f}%")
                output_lines.append(f"[bold]内存使用率:[/] {proc.memory_percent():.2f}%")
                output_lines.append(f"[bold]监听地址:[/] {url}")
                return output_lines
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            continue
    output_lines.append(f"\n[bold red]'{server_name}' is not running\n")
    return output_lines
